$(function () {
    var map = QXMap.Map('mapContainer', {
        zoom: 10,
        center: [120.8, 27.952],
        maptype: QMAP_NORMAL_MAP
    });
    var result;

    map.addControl(new QXMap.LatlngControl("lnglatInfoControl", {
        position: "bottomright"
    }));
    //调用港区函数
    draw();
    //调用航线
    drawchannel();
    //权限登录的回车事件
    $(document).keypress(function(e) {
        if(e.keyCode==13){
            login()
        }
    })
        //能见度
    // visbility()
    //选择显示信息
    $(".channel").on("click", "li", function () {
        var index = $(this).index();
        if (index == 0) {
            if ($(this).html() == "显示站点") {
                $("[toggle='pointg']").css("display",'block')
                $(".pointdiv,.wind").removeClass("hide")
                if ($('svg g').hasClass("pointg")) ;$(this).html("隐藏站点")

            } else {
                $("[toggle='pointg']").css("display",'none')
                $(".pointdiv,.wind").addClass("hide")
                $(this).html("显示站点")
            }
        } else if (index === 1) {
            if ($(this).html() == "显示航道") {
                $("[toggle='polyline']").css("display",'block')
                $(".polyline-text").removeClass("hide")
                // $(".pointdiv").removeClass("hide")
                $(this).html("隐藏航道")
            } else {
                $("[toggle='polyline']").css("display",'none')
                $(".polyline-text").addClass("hide")
                // $(".pointdiv").addClass("hide")
                $(this).html("显示航道")
            }
        } else {
            if ($(this).html() == "隐藏港区") {
                $("[toggle='polygon']").css("display",'none')
                // $(".polygon-text").addClass("hide")
                // $(".pointdiv").removeClass("hide")
                $(this).html("显示港区")
            } else {
                $("[toggle='polygon']").css("display",'block')

                // $(".polygon-text").removeClass("hide")
                // $(".pointdiv").addClass("hide")
                $(this).html("隐藏港区")
            }
        }
    })
    // 二级菜单切换
    $("#nav").on("click", 'li', function () {
        var index = $(this).index();
        $(this).addClass("active").siblings(".active").removeClass("active");
        $("#visi,.colorCode").removeClass("show").addClass("hide")
        if (index === 0) {
            result.abort();
            rain()
            $(".wind").remove()
            $("#selRain").selfShow()
        } else if (index === 1) {
            result.abort();
            $("#selWind").selfShow()
            $(".wind").remove()
            wind()
        } else if (index === 2) {
            result.abort();
            $(".wind").remove()
            $(".pointdiv,.pointg").remove()
            $("[toggle='pointg']").remove()
            viisi()
            $("#visi").addClass("show").removeClass("hide")
            $("#selVisibility").selfShow()
        } else if (index == 3) {
            result.abort();
            $(".wind").remove()
            temp()
            $("#selTemp").selfShow()
        }
    })
    $(".selectList").mouseenter(function () {
        $(this).find("ul").removeClass("hide")
    })
    //页面加载启动降雨
    rain()
    //函数的封装
    //降雨选择3,6,12,24显示信息
    function rain() {
        $("#selRain,#selWind,#selVisibility").unbind();
        QXMap.removeGridMapProduct();
        QXMap.removeVectorMapProduct();
        var url = "/wzdisplay/statistics/query?element=Pre_Sum_1h&time=" + getMinTime()

        drawStation(url, "mm", '#333')
        //根据不同的value值选择显示不同降雨的时间
        $("#selRain").on("click", "li", function () {
            $(this).parent().siblings().find("span").html($(this).html())
            var index = $(this).index()
            $(this).parent().addClass("hide")
            if (index == 0) {
                // var url="/wzdisplay/site/getSite" ;
                var url = "/wzdisplay/statistics/query?element=Pre_Sum_3h&time=" + getMinTime()
                drawStation(url, "mm", '#333')
            } else if (index == 1) {
                var url = "/wzdisplay/statistics/query?element=Pre_Sum_6h&time=" + getMinTime()
                drawStation(url, "mm", '#333')
            } else if (index == 2) {

                var url = "/wzdisplay/statistics/query?element=Pre_Sum_12h&time=" + getMinTime()
                drawStation(url, "mm", '#333')
            } else if (index == 3) {
                var url = "/wzdisplay/statistics/query?element=Pre_Sum_24h&time=" + getMinTime()
                drawStation(url, "mm", '#333')
            }
        })
    }

    //风力监测
    function wind() {
        $("#selRain,#selWind,#selVisibility").unbind();
        QXMap.removeGridMapProduct();
        QXMap.removeVectorMapProduct();
        var url = "/wzdisplay/hour/query?element=ExMaxWindV&pastH=3&type=max"
        drawStation(url, "m/s", 'transparent')
        windd("/wzdisplay/hour/query?element=ExMaxWindD&pastH=3&type=max")
        //根据不同的value值选择显示不同风力的时间
        $("#selWind").on("click", "li", function () {
            $(this).parent().siblings().find("span").html($(this).html())
            var index = $(this).index()
            $(this).parent().addClass("hide")
            if (index == 0) {
                var url = "/wzdisplay/hour/query?element=ExMaxWindV&pastH=3&type=max"
                drawStation(url, "m/s", 'transparent')
                $(".wind").remove()
                windd("/wzdisplay/hour/query?element=ExMaxWindD&pastH=3&type=max")
                //$(".wind").removeClass("hide")
            } else if (index == 1) {
                $(".wind").remove()
                var url = "/wzdisplay/hour/query?element=ExMaxWindV&pastH=6&type=max"
                drawStation(url, "m/s", 'transparent')
                windd("/wzdisplay/hour/query?element=ExMaxWindD&pastH=6&type=max")
            } else if (index == 2) {
                $(".wind").remove()
                var url = "/wzdisplay/hour/query?element=ExMaxWindV&pastH=12&type=max"
                drawStation(url, "m/s", 'transparent')
                windd("/wzdisplay/hour/query?element=ExMaxWindD&pastH=12&type=max")
            } else if (index == 3) {
                $(".wind").remove()
                var url = "/wzdisplay/hour/query?element=ExMaxWindV&pastH=24&type=max"
                drawStation(url, "m/s", 'transparent')
                windd("/wzdisplay/hour/query?element=ExMaxWindD&pastH=24&type=max")
            }
        })
    }
    //能见度
    function viisi() {

        $("#selRain,#selWind,#selVisibility").unbind();
        visbilityAjax('vis')
        // var url = "/wzdisplay/hour/query?element=Visibility&pastH=3&type=max"
        // drawStation(url, "Km", '#333')
        // var time = oneTime();
        // visbility('vis', time)
        //根据不同的value值选择显示不同能见度的时间
        $("#selVisibility").on("click", "li", function () {
            var index = $(this).index()
            $(this).parent().addClass("hide")
            $(this).parent().siblings().find("span").html($(this).html())

            if (index == 0) {
                visbilityAjax('vis')
                // visbility('vis', time)
                // var url="/wzdisplay/site/getSite" ;
                // var url = "/wzdisplay/hour/query?element=Visibility&pastH=3&type=min"
                // drawStation(url, "Km", '#333')
            }
            else if (index == 1) {
                visbilityAjax('vis24')
                // visbility('vis24', time)
                // var url = "/wzdisplay/hour/query?element=Visibility&pastH=24&type=min"
                // drawStation(url, "Km", '#333')
            }
        })
    }

    //绘制航线
    function drawchannel() {
        var luxiToDamen = {
            name: "鹿西岛至大门岛",
            center: {lng: 121.162, lat: 28.00},
            points: [{lng: 121.226145, lat: 27.990442}, {lng: 121.10285, lat: 27.987799}]
        }

        var luxiToDongtou = {
            name: "鹿西岛至洞头本岛",
            center: {lng: 121.192, lat: 27.907},
            points: [{lng: 121.226145, lat: 27.990442}, {lng: 121.170905, lat: 27.823867}]
        }

        var ruianToBeidao = {
            name: "瑞安至北麂岛",
            center: {lng: 120.950, lat: 27.690},
            points: [{lng: 120.655545, lat: 27.750708}, {lng: 121.216657, lat: 27.631206}]
        }

        var ruianToNandao = {
            name: "瑞安至南麂岛",
            center: {lng: 120.838, lat: 27.639},
            points: [{lng: 120.655545, lat: 27.750708}, {lng: 121.084864, lat: 27.471669}]
        }

        var aoToNandao = {
            name: "鳌江至南麂岛",
            center: {lng: 120.799, lat: 27.537},
            points: [{lng: 120.564605, lat: 27.590765}, {lng: 121.084864, lat: 27.471669}]
        }
        addPolyline(luxiToDamen, "green", .8)
        addPolyline(luxiToDongtou, "green", .8)
        addPolyline(ruianToBeidao, "green", .8)
        addPolyline(ruianToNandao, "green", .8)
        addPolyline(aoToNandao, "green", .8)
    }

    //地图多线段封装
    //points点的集合，fillColor线的颜色
    function addPolyline(points, fillColor, opacity) {
        var polylineOptions =
            {
                color: fillColor,
                weight: 10,
                fillColor: fillColor,
                opacity: opacity,
                fillopacity: 0.8,
                isfill: true
            }
        var polyline = QXMap.PolyLine(points.points, polylineOptions, function () {

        });
        var xy = map.getPixelFromLonLat(points.center);
        map.addMarkerLayer(polyline);
        $(polyline._container).attr("toggle","polyline").css("display","none");

        //绘制航道中心点
        var markOptions =
            {
                showlabel: true,
                radius: 3,
                direction: "right",
                color: 'transparent',
                content: points.name,
                fillColor: 'red'
            }
        mark = QXMap.CircleMarker(points.center, markOptions, function () {
        });
        map.addMarkerLayer(mark)
        $(mark.label._container).addClass("polyline-text hide");
    };

    //绘制监测站
    function drawStation(url, U, color) {
        result = $.ajax({
            url: url,
            success: function (data) {
                $(".pointdiv,.pointg").remove()
                $("[toggle='pointg']").remove()
                if (data.returnCode == 0) {
                    for (var i = 0, list = data.siteList; i < list.length; i++) {
                        (function (i) {
                            if(i.weather.value==null)i.weather.value=-999
                            var markOptions =
                                {
                                    showlabel: true,
                                    radius: 3,
                                    direction: "right",
                                    color: color,
                                    content: i.stationName + " " + i.weather.value + U,
                                }
                            mark = QXMap.CircleMarker(i, markOptions, function (e) {
                            });
                            map.addMarkerLayer(mark)
                            if ($(".channel li").eq(0).html() == "显示站点") {
                                $(mark.label._container).addClass("pointdiv hide")
                                $(mark._container).attr("toggle","pointg").css("display","none")

                            } else {
                                $(mark.label._container).addClass("pointdiv")
                                $(mark._container).attr("toggle","pointg")
                            }
                        })(list[i])
                    }
                } else {
                    alert("站点显示失败")
                }
            }
        })
    }

    //绘制港区
    function draw() {
        var polygonOptions =
            {
                color: '#0033ff',
                weight: 3,
                fillColor: '#83AEFF',
                opacity: .3,
                fillopacity: 0,
                isfill: true
            }
        var changNan = {
            name: "苍南港区",
            center: {lng: 120.662, lat: 27.503},
            points: "120.645762,27.491951,120.649499,27.498617,120.666747,27.497079,120.68112,27.492977,120.684282,27.501949,120.664447,27.507589,120.64835,27.506307,120.642313,27.499642"
        }

        var pingyang = {
            name: "平阳港区",
            center: {lng: 120.611, lat: 27.596},
            points: "120.600919,27.602132,120.60135,27.591759,120.618454,27.582026,120.622047,27.59765"
        }

        var rui = {
            name: "瑞安港区",
            center: {lng: 120.665, lat: 27.736},
            points: "120.624419,27.758819,120.68651,27.702031,120.704619,27.72301,120.645116,27.769559"
        }
        var jiang = {
            name: "瓯江港区",
            center: {lng: 120.886, lat: 27.987},
            points: "120.77,27.98,120.90,28.01,121.00,27.93,120.85,27.97"
        }
        var daxiao = {
            name: "大小门岛港区",
            center: {lng: 121.080, lat: 27.977},
            points: "121.053306,27.951214,121.048706,27.991029,121.082472,28.017414,121.09742,28.008229,121.086651,27.985415,121.160085,27.964336,121.156061,27.956679,121.101599,27.945597"
        }
        var leqing = {
            name: "乐清湾港区",
            center: {lng: 121.012, lat: 28.149},
            points: "120.95,27.98,121.07,28.13,121.13,28.26,120.97,28.15"
        }
        var zhuangy = {
            name: "状元岙港区",
            center: {lng: 121.096, lat: 27.882},
            points: "121.044107,27.881756,121.16139,27.910362,121.133794,27.879202,121.074578,27.849055"
        }
        drawpolygon(changNan, polygonOptions)
        drawpolygon(pingyang, polygonOptions)
        drawpolygon(rui, polygonOptions)
        drawpolygon(jiang, polygonOptions)
        drawpolygon(daxiao, polygonOptions)
        drawpolygon(leqing, polygonOptions)
        drawpolygon(zhuangy, polygonOptions)
    }

    //绘制多边形
    function drawpolygon(str, polygonOptions) {
        var arr = str.points.split(",");
        var psts = [];
        for (var i = 0; i < arr.length; i++) {
            if (i % 2 == 0) {
                psts.push({lng: arr[i], lat: arr[i + 1]})
            }
        }
        var xy = map.getPixelFromLonLat(str.center);
        var html = '<div class="sing qxmap-zoom-animated qxmap-drag-target" tabindex="0" style="left:' + xy.x + 'px ;top:' + xy.y + 'px">' + str.name + '</div>'
        // $("#mapContainer").append(html)
        var polyline = QXMap.Polygon(psts, polygonOptions, function () {
        });
        // $(mark.label._container).addClass("pointdiv hide")
        map.addVectorLayer(polyline)
        // $(polyline._container).addClass("polygon");
        $(polyline._container).attr("toggle","polygon");

        //绘制多边形中心点
        var markOptions =
            {
                showlabel: true,
                radius: 3,
                direction: "right",
                color: 'red',
                content: str.name,
                fillColor: 'red',
                textColor: "red"
            }
        mark = QXMap.CircleMarker(str.center, markOptions, function () {
            // $(".polygon-point").unbind()
        });
        map.addMarkerLayer(mark)

        $(mark._container).addClass("polygon-point")
        $(mark.label._container).addClass("polygon-text");
    }

    map.addMapChangeListener(function () {

        if (map.map.getZoom() <= 8) {
            $("[toggle='pointg']").css("display","none")
            $(".pointdiv").addClass("hide")
            $(".channel li").eq(0).html("显示站点")
        } else if (map.map.getZoom() >= 12) {
            $("[toggle='pointg']").css("display",'block')
            $(".pointdiv").removeClass("hide")
            $(".channel li").eq(0).html("隐藏站点")
        }
    })

    //绘制整点整分的时间
    function getMinTime() {
        var date = new Date();
        var day = date.getDate()
        var hour = date.getHours();
        var month = (date.getMonth() + 1);
        hour = hour > 9 ? hour : '0' + hour
        month = month > 9 ? month : '0' + month
        day = day > 9 ? day : '0' + day;
        var min = date.getMinutes() + "";
        min = min[0] + "0";
        return date.getFullYear() + "" + month + "" + day + "" +
            hour + "" + min + "00";
    }

    //格点数据能见度
    function visbility(vis, time) {
        QXMap.removeGridMapProduct();
        QXMap.removeVectorMapProduct();
        var mapProductOptions = {
            productcategory: vis,
            time: time,
            regioncode: '330000',
            method: 'SURF_ZJ_CTR_MUL_HOR',
            interface: 'getSurfEleByTimeAndRegionCode',
            key: 'zjwlzx',
            pwd: '123',
            level: 0,
            gridmethod: 'SURF_ZJ_GRID_MUL_HOR',
            gridinterface: 'getGridEleInRectByTimeAndLevelAndValidtime',
            nlat: 32,
            slat: 22,
            wlon: 116,
            elon: 124,
            validtime: 0,
            isshowzero: false,
            isshowcontrol: true,
            position: "topright"
        }
        var product = QXMap.addVectorMapProduct(mapProductOptions, function (data) {
            var da = data._data;
            var r = [];
            for (var i = 0; i < da.length; i++) {
                for (var j = i + 1; j < da.length; j++)
                    if (da[i].color === da[j].color) j = ++i;
                r.push(da[i]);
            }
            addWindColorCode("能见度", r, "m")
            $(".colorCode").removeClass('hide').addClass("show")
            if (data == null) return;
            //QXMap.showValueClassByType(36.0);
        });

    }

    //能见度的色标
    function addWindColorCode(title, colorCode, U) {
        var html = ' <p>' + title + '</p><ul>'
        if (colorCode.join("")) {
            for (var i = 0; i < colorCode.length; i++) {
                var r = colorCode[i].color.lastIndexOf(",")

                html += '<li style="width:65px">' +
                    '<span  style="background: rgb(' + colorCode[i].color.slice(0, r) + ')"></span>' +
                    '<span>' + colorCode[i].value + U + '</span>' +
                    '</li>'
            }
            html += "</ul>"
            $(".colorCode").html(html)
        }
    }
    //格点数据能见度返回数组
    function visbilityAjax(vis){
        var time = oneTime()
        var url='http://10.135.30.116:8080/ZJDataCenter/api/SURF_ZJ_CTR_MUL_HOR/getSurfEleTimeListByTime?userid=zjwlzx&pwd=123&productcategory=vis&time='+time+'&timetype=D&admincodes=330000&level=0&elements=time&limitcnt=100&dataformat=json'
        $.ajax({
            type:'get',
            url:url,
            success:function(data){
                if(data.returnCode==0){
                    for(var i=0,html='';i<data.DS.length;i++){
                        html+='<li time="'+data.DS[i].time+'">'+i+'时发布'+'</li>'
                    }
                    $("#visi ul").html(html)
                    visbilityTime(vis)
                    $("#visi p span").html("0时发布")
                }

            }
        })
    }

    function visbilityTime(vis){
        $("#visi").unbind()
        visbility(vis, $("#visi ul li").eq(0).attr('time'))
        $("#visi").mouseenter(function(){
            $(this).find(".rain-cn").addClass('show').removeClass("hide")
        })
        $("#visi").on("click","li",function(){

            $('#visi').find('p span').html($(this).html())
            var time=$(this).attr("time")
            visbility(vis, time)
            // $(this).parent().addClass('hide').removeClass("show")
            $(this).parent().parent().addClass('hide').removeClass("show")
        })
    }
    //获得当前的时间
    function oneTime() {
        var date = new Date();
        var day = date.getDate();
        var month = date.getMonth() + 1;
        // date.setDate(date.getDate()-1)
        date.setHours(date.getHours() - 1)
        var hour = date.getHours();

        hour = hour > 9 ? hour : '0' + hour;
        month = month > 9 ? month : '0' + month;
        day = day > 9 ? day : '0' + day;
        return date.getFullYear() + '' + month + '' + day + '' + hour + "0000"
    }

    //增加风向
    function windd(url) {
        result = $.ajax({
            type: "get",
            url: url,
            success: function (data) {
                if (data.returnCode == 0) {
                    for (var i = 0, list = data.siteList; i < list.length; i++) {
                        var point = new QXMap.Point(list[i].lng, list[i].lat);
                        var markOptions =
                            {
                                wd: list[i].weather.value,//风向
                                wv: 32,//风速
                                color: '#333', //风向颜色
                                showlabel: true, //是否显示标签
                                direction: "top" //显示方向

                            }
                        var markLabel = QXMap.WindMarker(point, markOptions, function () {
                        });
                        map.addMarkerLayer(markLabel);
                        if ($(".channel li").eq(0).html() == "显示站点") {
                            $(markLabel._icon).addClass("wind hide")
                        } else {
                            $(markLabel._icon).addClass("wind")
                        }
                    }
                }

                // data.forEach(function(val){

                //     var point = new QXMap.Point(120, 29.3);
                //     var markOptions =
                //         {
                //             wd: 230,//风向
                //             wv: 32,//风速
                //             color: '#fff000', //风向颜色
                //             showlabel: true, //是否显示标签
                //             direction: "top",  //显示方向
                //             content: 'dasdsfsd' //内容
                //         }
                //     var markLabel = QXMap.WindMarker(point, markOptions, function () { });
                //     // map.addMarkerLayer(markLabel);
                //
                // })
            }
        })
    }

    function temp() {
        //根据不同的value值选择显示不同的时间段的温度
        QXMap.removeGridMapProduct();
        QXMap.removeVectorMapProduct();
        var url = "/wzdisplay/hour/query?element=DryBulTemp&pastH=3&type=max"
        drawStation(url, "℃", '#333')
        $("#selTemp").on("click", "li", function () {
            $(this).parent().siblings().find("span").html($(this).html())
            var index = $(this).index()
            $(this).parent().addClass("hide")
            if (index == 0) {

                var url = "/wzdisplay/hour/query?element=DryBulTemp&pastH=3&type=max"
                drawStation(url, "℃", '#333')
            } else if (index == 1) {
                var url = "/wzdisplay/hour/query?element=DryBulTemp&pastH=6&type=max"
                drawStation(url, "℃", '#333')
            } else if (index == 2) {
                var url = "/wzdisplay/hour/query?element=DryBulTemp&pastH=12&type=max"
                drawStation(url, "℃", '#333')
            } else if (index == 3) {
                var url = "/wzdisplay/hour/query?element=DryBulTemp&pastH=24&type=max"
                drawStation(url, "℃", '#333')
            }
        })
    }
    //获得权限页面
    $("#login button.btn").click(function(){
        login()
    })
    //设置cookie
    function setCookie()
    {
        var Days = 30;
        var exp = new Date();
        exp.setTime(exp.getTime() + Days*24*60*60*1000);
        document.cookie ="login";
    }
    function login(){
        var val=$("#pname").val();
        var password=$("#password").val();
        if(val!=password){
            alert("姓名密码或错误");
            return;
        }
        if(/^wzqx$/.test(val)){

            $("#login").fadeOut()
            setCookie()
            $("body").css("overflow-y","auto")
            $(".w-content").removeClass("hide")
        }else if(/^ghyh$/.test(val)){
            setCookie()
            $("body").css("overflow-y","auto")
            $(".w-content").removeClass("hide")
            $("#login").fadeOut()

        }else{
            alert("你无权限")
        }

    }
    //获得cookie

    //jquery插件
    jQuery.fn.selfShow = function () {
        this.removeClass("hide").addClass("show").siblings(".show").removeClass("show").addClass("hide")
    }
})